package com.nmgsr.ptmsapp.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import com.nmgsr.beans.entity.SysNotice;

import java.util.List;

public class CustomTextSwitcher extends TextSwitcher implements ViewSwitcher.ViewFactory {

    private Context mContext;
    private List<SysNotice> MsgList;
    private final long DEFAULT_TIME_SWITCH_INTERVAL = 1000;//1s
    private long mTimeInterval = DEFAULT_TIME_SWITCH_INTERVAL;
    private int mCurrentIndex = 0;
    private String ID;

    public CustomTextSwitcher(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        setFactory(this);
    }

    public CustomTextSwitcher setInAnimation(int animationResId) {
        Animation animation = AnimationUtils.loadAnimation(this.mContext, animationResId);
        setInAnimation(animation);
        return this;
    }

    public CustomTextSwitcher setOutAnimation(int animationResId) {
        Animation animation = AnimationUtils.loadAnimation(this.mContext, animationResId);
        setOutAnimation(animation);
        return this;
    }


    /**
     * 通知/公告数据绑定
     *
     * @param msgList
     * @return
     */
    public CustomTextSwitcher bindData(List<SysNotice> msgList) {
        this.MsgList = msgList;
        return this;
    }

    public void startSwitch(long timeInterval) {
        this.mTimeInterval = timeInterval;
        if (MsgList != null && MsgList.size() != 0) {
            mSwitchHandler.sendEmptyMessage(0);
        } else {
            throw new RuntimeException("data is empty");
        }
    }

    /**
     * 工厂类中创建TextView供给TextSwitcher使用
     *
     * @return
     */
    @Override
    public View makeView() {
        TextView view = new TextView(this.mContext);
        view.setTextSize(14);
        view.setTextColor(0xffBD3124);
        return view;
    }

    @SuppressLint("HandlerLeak")
    private final Handler mSwitchHandler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            int index = mCurrentIndex % MsgList.size();
            mCurrentIndex++;
            setText(MsgList.get(index).getTitle());
            setID(MsgList.get(index).getId());
            sendEmptyMessageDelayed(0, mTimeInterval);
        }

    };

    public String getID() {
        return ID;
    }

    public void setID(String ID) {
        this.ID = ID;
    }
}
